local H = require "packages/new_heg/util"
local U = require "packages/utility/utility"
local extension = Package:new("movement")
extension.extensionName = "hegemony_diy"
extension.game_modes_whitelist = { 'nos_heg_mode', 'new_heg_mode' }

Fk:loadTranslationTable{
  ["movement"] = "日月交辉·遣",
  ["wk_heg"] = "日月",
}

--- 借调 （需要修复和变更的兼容）
---@param room Room
---@param player ServerPlayer
---@param target ServerPlayer
---@param deputyName string
---@param kingdom string
---@param isDeputy boolean
local function DoGiveDeputy(room, player, target, deputyName, kingdom, isDeputy)
  local orig_before = isDeputy and (player.deputyGeneral or "") or player.general
  orig_before = Fk.generals[orig_before]
  local orig_skills_before = orig_before and orig_before:getSkillNameList() or {}
  -- H.removeGeneral(room, player, isDeputy)

  player:setMark("CompanionEffect", 0)
  player:setMark("HalfMaxHpLeft", 0)
  player:doNotify("SetPlayerMark", json.encode{ player.id, "CompanionEffect", 0})
  player:doNotify("SetPlayerMark", json.encode{ player.id, "HalfMaxHpLeft", 0})
  player:revealGeneral(isDeputy, true) -- 先摆
  if room.logic:trigger("fk.GeneralRemoving", player, isDeputy) then return false end
  local orig = isDeputy and (player.deputyGeneral or "") or player.general
  if orig:startsWith("blank_") then return false end
  orig = Fk.generals[orig]
  local orig_skills = orig and orig:getSkillNameList() or {}
  local new_general = orig.gender == General.Male and "blank_shibing" or "blank_nvshibing"
  orig_skills = table.map(orig_skills, function(e)
    return "-" .. e
  end)
  room:handleAddLoseSkills(player, table.concat(orig_skills, "|"), nil, false)
  if isDeputy then
    room:setPlayerProperty(player, "deputyGeneral", new_general)
    room:setPlayerMark(player, "__heg_deputy", new_general)
  else
    room:setPlayerProperty(player, "general", new_general)
    room:setPlayerMark(player, "__heg_general", new_general)
  end
  player:filterHandcards()
  room:sendLog{
    type = "#GeneralRemoved",
    from = player.id,
    arg = isDeputy and "deputyGeneral" or "mainGeneral",
    arg2 = orig.name,
  }
  -- room:returnToGeneralPile({orig.name})
  room.logic:trigger("fk.GeneralRemoved", player, orig.name)

  room:handleAddLoseSkills(target, table.concat(orig_skills_before, "|"), nil, false)
  room:setPlayerMark(target, "@wk_give_deputy", deputyName)
  room:setPlayerMark(target, "@wk_give_deputy_kingdom", kingdom)
end

--- 结束借调
---@param room Room
---@param player ServerPlayer
---@param skillName string
local function StopGiveDeputy(room, player, skillName)
  local orig_string = player:getMark("@wk_give_deputy")
  local orig = Fk.generals[orig_string]
  room:returnToGeneralPile({orig_string})
  local orig_skills = orig and orig:getSkillNameList() or {}
  orig_skills = table.map(orig_skills, function(e)
    return "-" .. e
  end)
  room:handleAddLoseSkills(player, table.concat(orig_skills, "|"), nil, false)

  local targets = table.map(table.filter(room.alive_players, function(p)
    return p.kingdom == player:getMark("@wk_give_deputy_kingdom") 
    and (p.deputyGeneral:startsWith("blank_") or p.general:startsWith("blank_")) end), Util.IdMapper)
  if #targets > 0 then
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#wk_give_deputy-choose", skillName, false)
    if #to > 0 then
      local target = room:getPlayerById(to[1])
      local choices = {}
      if target.deputyGeneral:startsWith("blank_") then
        table.insert(choices, "wk_give_deputy_back")
      end
      if target.general:startsWith("blank_") then
        table.insert(choices, "wk_give_main_back")
      end
      if #choices > 0 then
        local choice = room:askForChoice(player, choices, skillName)
        if choice == "wk_give_deputy_back" then
          room:changeHero(target, orig_string, false, true, true, false, false)
          room.logic:trigger("fk.GeneralTransformed", target, orig_string)
        else
          room:changeHero(target, orig_string, false, false, true, false, false)
          room.logic:trigger("fk.GeneralTransformed", target, orig_string)
        end
      end
    end
  end

  room:setPlayerMark(player, "@wk_give_deputy", 0)
  room:setPlayerMark(player, "@wk_give_deputy_kingdom", 0)
end

Fk:loadTranslationTable{
  ["@wk_give_deputy"] = "借调",
  ["@wk_give_deputy_kingdom"] = "属国",

  ["#wk_give_deputy-choose"] = "借调：选择该借调武将牌原所属国家一名有士兵牌的角色，结束借调并返还此武将牌于其",
}

--- 交换副将
---@param room Room
---@param player ServerPlayer
---@param target ServerPlayer
---@return boolean
local function SwapTwoPlayersDeputy(room, player, target)
  if not (player.deputyGeneral and target.deputyGeneral) then return false end
  if player.deputyGeneral == "anjiang" then player:revealGeneral(true, true) end
  if target.deputyGeneral == "anjiang" then target:revealGeneral(true, true) end
  local general1 = player.deputyGeneral
  local general2 = target.deputyGeneral
 
  room:changeHero(player, "blank_shibing", false, true, false, false, false)
  room:changeHero(target, "blank_shibing", false, true, false, false, false)
  room:changeHero(player, general2, false, true, true, false, false)
  room:changeHero(target, general1, false, true, true, false, false)
  return true
end
 

local zhaoyan = General(extension, "wk_heg__zhaoyan", "wei", 3)
local lingxie = fk.CreateTriggerSkill{
  name = "wk_heg__lingxie",
  anim_type = "special",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and table.find(player.room.alive_players, function (p) return H.compareKingdomWith(p, player) and p ~= player end)) then return false end
    local targets = {}
    player.room.logic:getActualDamageEvents(1, function(e)
      local damage = e.data[1]
      if player == damage.to then
        table.insertIfNeed(targets, damage.to.id)
      end
      return false
    end)
    return #targets > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function (p) return H.compareKingdomWith(p, player) end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 2, 2, "#wk_heg__lingxie-choose", self.name, false)
    local to1 = room:getPlayerById(tos[1])
    local to2 = room:getPlayerById(tos[2])
    SwapTwoPlayersDeputy(room, to1, to2)
    local to1general = Fk.generals[to1.general]
    local to1deputy = Fk.generals[to1.deputyGeneral]
    local to2general = Fk.generals[to2.general]
    local to2deputy = Fk.generals[to2.deputyGeneral]

    if ((to1general.maxHp + to1deputy.maxHp) % 2 == 1) and to1:getMark("@!yinyangfish") == 0 then
      H.addHegMark(room, to1, "yinyangfish")
    end
    if to1general:isCompanionWith(to1deputy) and to1:getMark("@!companion") == 0 then
      H.addHegMark(room, to1, "companion")
    end
    if ((to2general.maxHp + to2deputy.maxHp) % 2 == 1) and to2:getMark("@!yinyangfish") == 0 then
      H.addHegMark(room, to2, "yinyangfish")
    end
    if to2general:isCompanionWith(to2deputy) and to2:getMark("@!companion") == 0 then
      H.addHegMark(room, to2, "companion")
    end
  end,
}

local yanji = fk.CreateTriggerSkill{
  name = "wk_heg__yanji",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player ~= target and target.phase == Player.Play and not player:isKongcheng()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = player:getCardIds(Player.Hand)
    player:showCards(cards)
    local all_choices = {"wk_heg__yanji_black", "wk_heg__yanji_red"}
    local black = {}
    local red = {}
    for _, cid in ipairs(cards) do
      local card = Fk:getCardById(cid)
      if card.color == Card.Black then
        table.insertIfNeed(black, cid)
      end
      if card.color == Card.Red then
        table.insertIfNeed(red, cid)
      end
    end
    local choices = {}
    if #black > 0 and not player:prohibitUse(Fk:cloneCard("slash")) then
      table.insert(choices, "wk_heg__yanji_black")
    end
    if #red > 0 and not player:prohibitUse(Fk:cloneCard("peach")) and target.hp < target.maxHp then
      table.insert(choices, "wk_heg__yanji_red")
    end
    if #choices == 0 then return false end
    local choice = room:askForChoice(player, choices, self.name, nil, nil, all_choices)
    if choice == "wk_heg__yanji_black" then
      room:useVirtualCard("slash", black, player, target, self.name)
    else
      room:useVirtualCard("peach", red, player, target, self.name)
    end
    if (player.general == "wk_heg__zhaoyan" or player.deputyGeneral == "wk_heg__zhaoyan") and target:getMark("@wk_give_deputy") == 0 then
      if player.dead or target.dead then return end
      local isDeputy = H.inGeneralSkills(player, self.name)
      if isDeputy then
        DoGiveDeputy(room, player, target, "wk_heg__zhaoyan", player.kingdom, isDeputy == "d")
      end
      room:setPlayerMark(player, "wk_give_deputy_zhaoyan", 1)
    end
  end,
}

local yanji_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__yanji_delay",
  anim_type = "special",
  events = {fk.TurnStart},
  can_trigger = function(self, event, target, player, data)
    return target:getMark("wk_give_deputy_zhaoyan") == 1 and player:getMark("@wk_give_deputy") == "wk_heg__zhaoyan"
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    StopGiveDeputy(player.room, player, self.name)
    player.room:setPlayerMark(target, "wk_give_deputy_zhaoyan", 0)
  end,
}

zhaoyan:addSkill(lingxie)
yanji:addRelatedSkill(yanji_delay)
zhaoyan:addSkill(yanji)
Fk:loadTranslationTable{
  ["wk_heg__zhaoyan"] = "赵俨",
  ["#wk_heg__zhaoyan"] = "",
  ["designer:wk_heg__zhaoyan"] = "635&教父",

  ["wk_heg__lingxie"] = "令协",
  [":wk_heg__lingxie"] = "每回合结束时，若你此回合内受到过伤害，你可令两名你势力相同的角色交换副将并重新结算对应的国战标记。",
  ["wk_heg__yanji"] = "严纪",
  [":wk_heg__yanji"] = "其他角色的出牌阶段开始时，你可以展示所有手牌并选择将其中所有红色/黑色牌当【桃】/【杀】对其使用，然后你借调此武将牌于其至你回合开始。<br />"..
  "<font color = 'orange'>借调：借调角色执行借调流程时，移除对应的武将牌并将之置于目标角色的借调区内，视为该角色拥有此武将牌，借调区内的武将牌不为主副将且不能被移除、暗置和变更。"..
  "借调结束后，目标角色选择借调武将牌原本所属国家所有角色的一张士兵牌，令此士兵牌变更为借调武将牌。</font>",

  ["#wk_heg__lingxie-choose"] = "令协：选择两名与你势力相同的角色交换副将",
  ["wk_heg__yanji_black"] = "将黑色牌当【杀】使用",
  ["wk_heg__yanji_red"] = "将红色牌当【桃】使用",
  
  ["#wk_heg__yanji_delay"] = "严纪",

  ["$wk_heg__lingxie1"] = "",
  ["$wk_heg__lingxie2"] = "",
  ["$wk_heg__yanji1"] = "",
  ["$wk_heg__yanji2"] = "",
  ["~wk_heg__zhaoyan"] = "",
}

local zaoren = General(extension, "wk_heg__zaoren", "wei", 4)
local kenfeng = fk.CreateTriggerSkill{
  name = "wk_heg__kenfeng",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player ~= target and target.phase == Player.Finish
     and table.find(player.room.alive_players, function (p) return p:getHandcardNum() <= player:getHandcardNum() end)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function (p) return p:getHandcardNum() <= player:getHandcardNum() end), Util.IdMapper)
    if #targets > 0 then
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__kenfeng_choose")
      if #tos > 0 then
        local to = room:getPlayerById(tos[1])
        local cards = room:askForCard(to, 1, 1, true, self.name, true, ".|.|club", "#wk_heg__kenfeng_card")
        if #cards > 0 then
          room:moveCards({
            ids = cards,
            from = to.id,
            toArea = Card.DrawPile,
            moveReason = fk.ReasonJustMove,
            skillName = self.name,
            proposer = to.id,
            drawPilePosition = -1,
          })
          local draw_cards = to:drawCards(2, self.name)
          to:showCards(draw_cards)
          local need_give = {}
          for _, cid in ipairs(draw_cards) do
            local card = Fk:getCardById(cid)
            if card.suit == Card.Club then
              table.insertIfNeed(need_give, cid)
            end
          end
          local give_aim = table.map(table.filter(room.alive_players, function (p) return to:distanceTo(p) == 1 end), Util.IdMapper)
          if #need_give > 0 and #give_aim > 0 then
            local give_tos = room:askForChoosePlayers(to, give_aim, 1, 1, "#wk_heg__kenfeng_give", self.name, false)
            local give_to = room:getPlayerById(give_tos[1])
            room:obtainCard(give_to, need_give, false, fk.ReasonGive)
          end
        end
      end
    end
  end,
}

zaoren:addSkill(kenfeng)
Fk:loadTranslationTable{
  ["wk_heg__zaoren"] = "枣祗任峻",
  ["#wk_heg__zaoren"] = "",
  ["designer:wk_heg__zaoren"] = "静谦&教父",

  ["wk_heg__kenfeng"] = "垦丰",
  [":wk_heg__kenfeng"] = "其他角色的结束阶段，你可令一名手牌数不大于你的角色选择是否将一张♣牌置于牌堆底并摸两张牌，若如此做，其展示以此法获得的所有牌并将其中的♣牌交给一名其距离为1的角色。",

  ["#wk_heg__kenfeng_choose"] = "垦丰：你可以选择一名手牌数不大于体力值的角色，然后其可以将一张 梅花 牌置于牌堆底并摸两张牌",
  ["#wk_heg__kenfeng_card"] = "垦丰：你可以将一张 梅花 牌置于牌堆底，然后摸两张牌",
  ["#wk_heg__kenfeng_give"] = "垦丰：选择一名与你距离为1的角色，将以此法获得的所有 梅花 牌交给其",

  ["$wk_heg__kenfeng1"] = "",
  ["$wk_heg__kenfeng2"] = "",
  ["~wk_heg__zaoren"] = "",
}


local sunqian = General(extension, "wk_heg__sunqian", "shu", 3)
local shuomeng = fk.CreateTriggerSkill{
  name = "wk_heg__shuomeng",
  anim_type = "special",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and data.card and data.card.suit == Card.Heart
     and data.tos and table.find(TargetGroup:getRealTargets(data.tos), function(id) return id == player.id end)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if target.dead then return false end
    target:drawCards(1, self.name)
    if #target:getCardIds("he") >= 2 then
      local cards = room:askForCard(target, 2, 2, false, self.name, true, ".|.|heart,diamond|hand|.|.", "#wk_heg__shuomeng-give::"..player.id)
      if #cards == 2 then
        room:obtainCard(player, cards, false, fk.ReasonPrey)
        if (player.general == "wk_heg__sunqian" or player.deputyGeneral == "wk_heg__sunqian") and target:getMark("@wk_give_deputy") == 0 then
          if player.dead or target.dead then return end
          local isDeputy = H.inGeneralSkills(player, self.name)
          if isDeputy then
            DoGiveDeputy(room, player, target, "wk_heg__sunqian", player.kingdom, isDeputy == "d")
          end
          room:setPlayerMark(player, "wk_give_deputy_sunqian", 1)
        end
      end
    end
  end,
}

local shuomeng_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__shuomeng_delay",
  anim_type = "special",
  events = {fk.TurnStart},
  can_trigger = function(self, event, target, player, data)
    return target:getMark("wk_give_deputy_sunqian") == 1 and player:getMark("@wk_give_deputy") == "wk_heg__sunqian"
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    StopGiveDeputy(player.room, player, self.name)
    player.room:setPlayerMark(target, "wk_give_deputy_sunqian", 0)
  end,
}

local liance_viewas = fk.CreateViewAsSkill{
  name = "#wk_heg__yongyi_viewas",
  interaction = function()
    return UI.ComboBox {choices = {"alliance_feast"}}
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    return card
  end,
}

local yongyi = fk.CreateTriggerSkill{
  name = "wk_heg__yongyi",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.BeforeDrawCard, fk.BeforeChainStateChange},
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and player == target) then return false end
    -- if event == fk.TargetSpecified then
    if event == fk.BeforeChainStateChange then
      return not player.chained
    else
      return data.skillName == "alliance&" and not player:prohibitUse(Fk:cloneCard("alliance_feast"))
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.BeforeChainStateChange then
      return true
    else
      data.n = 0
      local success, dat = player.room:askForUseActiveSkill(player, "#wk_heg__yongyi_viewas", "#wk_heg__liance-choose", true)
      if success then
        local card = Fk.skills["#wk_heg__yongyi_viewas"]:viewAs({"alliance_feast"})
        room:useCard{
          from = player.id,
          tos = table.map(dat.targets, function(id) return {id} end),
          card = card,
        }
      end
      local cards = table.filter(player:getCardIds(Player.Hand), function (id) return Fk:getCardById(id).trueName == "slash" end)
      if #cards > 0 then
        room:recastCard(cards, player, self.name)
      end
      return true
    end
  end,
}

sunqian:addCompanions("hs__liubei")
shuomeng:addRelatedSkill(shuomeng_delay)
sunqian:addSkill(shuomeng)
yongyi:addRelatedSkill(liance_viewas)
sunqian:addSkill(yongyi)
Fk:loadTranslationTable{
  ["wk_heg__sunqian"] = "孙乾",
  ["#wk_heg__sunqian"] = "",
  ["designer:wk_heg__sunqian"] = "静谦&635&教父",

  ["wk_heg__shuomeng"] = "说盟",
  [":wk_heg__shuomeng"] = "当你成为其他角色使用红桃牌的目标结算后，你可令其摸一张牌，然后其可交给你两张红色牌，借调此武将牌于其至你回合开始。<br />"..
  "<font color = 'orange'>借调：借调角色执行借调流程时，移除对应的武将牌并将之置于目标角色的借调区内，视为该角色拥有此武将牌，借调区内的武将牌不为主副将且不能被移除、暗置和变更。"..
  "借调结束后，目标角色选择借调武将牌原本所属国家所有角色的一张士兵牌，令此士兵牌变更为借调武将牌。</font>",
  ["wk_heg__yongyi"] = "雍仪",
  [":wk_heg__yongyi"] = "锁定技，当你横置时，取消之；当你因“合纵”摸牌时，你改为视为使用一张【联军盛宴】然后重铸所有【杀】。",

  ["#ty_heg__shuomeng-give"] = "说盟：交给 %dest 1 张红桃手牌。",
  ["#wk_heg__shuomeng_delay"] = "说盟",
  ["#wk_heg__yongyi_viewas"] = "雍仪",
  ["wk_heg__shuomeng_give"] = "交给牌 借调孙乾",
  ["wk_heg__shuomeng_slash"] = "视为被使用【杀】",

  ["$wk_heg__shuomeng1"] = "你我唇齿相依，共御外敌，何如？",
  ["$wk_heg__shuomeng2"] = "今兵薄势寡，可遣某为使往说之。",
  ["$wk_heg__yongyi1"] = "君子不妄动，动必有道。",
  ["$wk_heg__yongyi2"] = "哎！将军过誉了！",
  ["~wk_heg__sunqian"] = "恨不能……得见皇叔早登大宝，咳咳咳……",
}

local guanxingzhangbao = General(extension, "wk_heg__guanxingzhangbao", "shu", 4)
local fuhun = fk.CreateTriggerSkill{
  name = "wk_heg__fuhun",
  frequency = Skill.Compulsory,
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target and data.card.trueName == "slash" and data.firstTarget
  end,
  on_use = function(self, event, target, player, data)
    data.disresponsiveList = data.disresponsiveList or {}
    for _, p in ipairs(player.room.alive_players) do
      if p ~= player and p.hp >= player.hp then
        table.insertIfNeed(data.disresponsiveList, p.id)
      end
    end
  end,
}

local fuhun_targetmod = fk.CreateTargetModSkill{
  name = "#wk_heg__fuhun_targetmod",
  frequency = Skill.Compulsory,
  anim_type = "offensive",
  bypass_times = function(self, player, skill, scope, card, to)
    return player:hasSkill(fuhun) and card and card.color == Card.Red and skill.trueName == "slash_skill"
  end,
  bypass_distances = function (self, player, skill, card, to)
    return player:hasSkill(fuhun) and card and card.color == Card.Black and skill.trueName == "slash_skill"
  end
}


fuhun:addRelatedSkill(fuhun_targetmod)
guanxingzhangbao:addSkill(fuhun)
Fk:loadTranslationTable{
  ["wk_heg__guanxingzhangbao"] = "关兴张苞",
  ["#wk_heg__guanxingzhangbao"] = "将门虎子",
  ["designer:wk_heg__guanxingzhangbao"] = "24&635",

  ["wk_heg__fuhun"] = "父魂",
  [":wk_heg__fuhun"] = "锁定技，你使用黑色/红色【杀】无距离限制/无次数限制；当你使用【杀】指定目标后，你令此牌不能被所有体力值不小于你的角色响应。",
  ["@wk_heg__fuhun"] = "父魂",
  ["@wk_heg__fuhun-phase"] = "父魂",

  ["$wk_heg__fuhun1"] = "不血父仇，誓不罢休！",
  ["$wk_heg__fuhun2"] = "承父遗志，横扫叛贼！",
  ["~wk_heg__guanxingzhangbao"] = "吾得父亲之遗志，未袭父亲之神勇。",
}


local kanze = General(extension, "wk_heg__kanze", "wu", 3)

local haozhu = fk.CreateTriggerSkill{
  name = "wk_heg__haozhu",
  anim_type = "special",
  events = {fk.Damaged, fk.HpLost, fk.HpRecover},
  can_trigger = function(self, event, target, player, data)
    if target == player or not player:hasSkill(self) then return false end
    local room = player.room
    local x = target:getMark("wk_heg__haozhu_record-turn")
    if x ~= 0 then return false end
    local hp_event = room.logic:getCurrentEvent()
    room.logic:getEventsOfScope(GameEvent.ChangeHp, 1, function (e)
      if e.data[1] ~= player then
        local reason = e.data[3]
        local game_event = nil
        if reason == "damage" then
          game_event = GameEvent.Damage
        elseif reason == "loseHp" then
          game_event = GameEvent.LoseHp
        elseif reason == "recover" then
          game_event = GameEvent.Recover
        else
          return true
        end
        local first_event = e:findParent(game_event)
        if first_event then
          x = first_event.id
          room:setPlayerMark(player, "wk_heg__haozhu_record-turn", x)
        end
        return true
      end
    end, Player.HistoryTurn)
    return hp_event.id == x and not target:isNude()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = room:askForCardsChosen(player, target, 1, 1, "he", self.name)
    room:obtainCard(player, cards, false, fk.ReasonPrey)
    if not player:isNude() then
      local cards2 = room:askForCardsChosen(player, player, 1, 1, "he", self.name)
      room:obtainCard(target, cards2, false, fk.ReasonGive)
    end
    if player.general == "wk_heg__kanze" or player.deputyGeneral == "wk_heg__kanze" then
      if player.dead or target.dead then return end
      local isDeputy = H.inGeneralSkills(player, self.name)
      if isDeputy and target:getMark("@wk_give_deputy") == 0 then
        DoGiveDeputy(room, player, target, "wk_heg__kanze", player.kingdom, isDeputy == "d")
      end
      -- room:setPlayerMark(player, "wk_give_deputy_kanze", 1)
    end
  end,
}

local haozhu_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__haozhu_delay",
  anim_type = "special",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return player == player.room.current and player:getMark("@wk_give_deputy") == "wk_heg__kanze"
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    StopGiveDeputy(player.room, player, self.name)
    -- player.room:setPlayerMark(target, "wk_give_deputy_luzhi", 0)
  end,
}

local hongru = fk.CreateTriggerSkill{
  name = "wk_heg__hongru",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.AfterSkillEffect, fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if event == fk.AfterSkillEffect then
      local skill_list = {
        -- 强袭 驱虎
        "hs__qiangxi", "quhu",
        -- 制衡 苦肉 反间 天义 缔盟 奋迅
        "hs__zhiheng", "hs__kurou", "ex__fanjian", "tianyi", "dimeng", "fenxun",
        -- 除疠 离间
        "hs__chuli", "hs__lijian",
        -- 挑衅 尚义
        "tiaoxin", "ld__shangyi",
        -- 断绁 问道
        "ld__duanxie", "wendao",
        -- 奇策 散谣 敛资
        "ld__qice", "ld__sanyao", "lianzi",
        -- 甘露 伪帝 挥鞭
        "ganlu", "ld__weidi", "huibian",
        -- 明伐 危盟 驳言 锋略
        "ty_heg__mingfa", "ty_heg__weimeng", "ty_heg__boyan", "ty_heg__fenglue",
        -- 盗书 妆戎 经合
        "ty_heg__daoshu", "ty_heg__zhuangrong", "ty_heg__jinghe",
        -- 凿运 劝进 荐言 调归 矜伐 排异 怀异 
        "zaoyun", "quanjin", "ld__jianyan", "ld__diaogui", "ld__jinfa", "ld__huaiyi", "ld__paiyi",
        -- 清识 丹心 安恤 
        "fk_heg__qingshiz", "fk_heg__danxin", "anxu",
        -- 风物 赂遗 肃朝 义叱
        "zx_heg__fengwu", "zx_heg__luyi", "zx_heg__suchao", "zx_heg__yichi",
        -- 抚蛮 拒关
        "wk_heg__fuman", "wk_heg__juguan"
      }
      return player:hasSkill(self) and player == target and table.contains(skill_list, data.name) and
       player:getMark(data.name.."__wk_heg__hongru-phase") == 0
    else
      if not (player:hasSkill(self) and player == target and player.phase == Player.Finish) then return false end
      local target_find = {}
      player.room.logic:getEventsOfScope(GameEvent.UseCard, 99, function (e)
        local use = e.data[1]
        if use.from == player.id then
          for _, id in ipairs(TargetGroup:getRealTargets(use.tos)) do
            if id ~= player.id then
              table.insertIfNeed(target_find, id)
            end
          end
        end
      end, Player.HistoryTurn)
      self.cost_data = target_find
      return #target_find > 0
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterSkillEffect then
      player:setSkillUseHistory(data.name, 0, Player.HistoryPhase)
      room:setPlayerMark(player, data.name.."__wk_heg__hongru-phase", 1)
    else
      local targets = self.cost_data
      room:sortPlayersByAction(targets)
      for _, pid in ipairs(self.cost_data) do
        local p = room:getPlayerById(pid)
        if player.dead then break end
        if not p:isNude() then
          local choices = {"wk_heg__hongru-give"}
          local card = Fk:cloneCard("slash")
          if not p:prohibitUse(card) then
            table.insert(choices, "wk_heg__hongru_slash")
          end
          table.insert(choices, "Cancel")
          local choice = room:askForChoice(p, choices, self.name)
          if choice == "wk_heg__hongru-give" then
            local cards = room:askForCardsChosen(p, p, 1, 1, "he", self.name)
            room:obtainCard(player, cards, false, fk.ReasonGive)
          elseif choice == "wk_heg__hongru_slash" then
            local cids = room:askForCard(p, 1, 1, true, self.name, false, nil, "#wk_heg__haozhu-slash:" .. player.id)
            if #cids > 0 then
              room:useVirtualCard("slash", cids, p, player, self.name)
            end
          end
        end
      end
    end
  end,
}

kanze:addCompanions("hs__huanggai")
haozhu:addRelatedSkill(haozhu_delay)
kanze:addSkill(haozhu)
kanze:addSkill(hongru)
Fk:loadTranslationTable{
  ["wk_heg__kanze"] = "阚泽",
  ["#wk_heg__kanze"] = "明悬月中",
  ["designer:wk_heg__kanze"] = "小曹神&教父",

  ["wk_heg__haozhu"] = "豪注",
  [":wk_heg__haozhu"] = "其他角色每回合内体力值首次变化后，你可获得其一张牌并交给其一张牌，然后你借调此武将牌于其至其回合结束。<br />"..
  "<font color = 'orange'>借调：借调角色执行借调流程时，移除对应的武将牌并将之置于目标角色的借调区内，视为该角色拥有此武将牌，借调区内的武将牌不为主副将且不能被移除、暗置和变更。"..
  "借调结束后，目标角色选择借调武将牌原本所属国家所有角色的一张士兵牌，令此士兵牌变更为借调武将牌。</font>",
  ["wk_heg__hongru"] = "鸿儒",
  [":wk_heg__hongru"] = "锁定技，①当你于回合内首次发动武将牌上“出牌阶段限一次”的技能后，你令此技能于此阶段发动次数+1；②结束阶段，本回合成为过你使用牌的目标的其他角色依次可选择一项：1.交给你一张牌；2.将一张牌当【杀】对你使用。",

  ["#wk_heg__haozhu_delay"] = "豪注",
  ["#wk_heg__haozhu-slash"] = "豪注：将一张牌当【杀】对 %src 使用",

  ["wk_heg__hongru-give"] = "交给牌",
  ["wk_heg__hongru_slash"] = "将一张牌当【杀】使用",

  ["$wk_heg__haozhu1"] = "吾有密信，特来献于将军。",
  ["$wk_heg__haozhu2"] = "将军若不信，可亲自验看！",
  ["$wk_heg__hongru1"] = "不知者，无罪。",
  ["$wk_heg__hongru2"] = "罚酒三杯，下不为例。",
  ["~wk_heg__kanze"] = "我早已做好了牺牲的准备。",
}

local weiwenzhugezhi = General(extension, "wk_heg__weiwenzhugezhi", "wu", 4)
local mingchao = fk.CreateActiveSkill{
  name = "wk_heg__mingchao",
  anim_type = "special",
  prompt = "#wk_heg__mingchao",
  interaction = function(self)
    local names = {}
    local all_choices = {"wk_heg__mingchao_show", "wk_heg__mingchao_discard"}
    for _, name in ipairs(all_choices) do
      if name == "wk_heg__mingchao_show" and Self:getMark("wk_heg__mingchao_used-turn") ~= 1  then
        table.insertIfNeed(names, name)
      end
      if name == "wk_heg__mingchao_discard" and Self:getMark("wk_heg__mingchao_used-turn") ~= 2  then
        table.insertIfNeed(names, name)
      end
    end
    if #names == 0 then return end
    return UI.ComboBox {choices = names, all_choices = all_choices }
  end,
  can_use = Util.TrueFunc,
  card_filter = function(self, to_select, selected)
    if not (Fk:currentRoom():getCardArea(to_select) == Player.Hand and Fk:getCardById(to_select):getMark("@@wk_heg__mingchao_shown-inhand-turn") == 0) then return false end
    if self.interaction.data:startsWith("wk_heg__mingchao_discard") then
      return not Self:prohibitDiscard(to_select)
    end
    return true
  end,
  target_filter = Util.FalseFunc,
  card_num = function(self)
    return Self:usedSkillTimes(self.name) + 1
  end,
  target_num = 0,
  on_use = function(self, room, effect)
    if not self.interaction.data then return end
    local player = room:getPlayerById(effect.from)
    local card = effect.cards
    if self.interaction.data:startsWith("wk_heg__mingchao_show") then
      player:showCards(card)
      for _, id in ipairs(card) do
        room:setCardMark(Fk:getCardById(id), "@@wk_heg__mingchao_shown-inhand-turn", 1)
      end
      local to = player
      if not to:isKongcheng() then
        local extra_data = {bypass_times = true}
        local availableCards = {}
        for _, id in ipairs(card) do
          local card = Fk:getCardById(id)
          if not player:prohibitUse(card) and player:canUse(card, extra_data) then
            table.insertIfNeed(availableCards, id)
          end
        end
         local use = U.askForUseRealCard(room, player, availableCards, ".", self.name, "#wk_heg__dingjian-use", {extra_use = true}, true)
        if use then
          room:useCard(use)
        end
      end
      room:setPlayerMark(player, "wk_heg__mingchao_used-turn", 1)
    else
      room:throwCard(card, self.name, player, player)
      player:drawCards(1, self.name)
      room:setPlayerMark(player, "wk_heg__mingchao_used-turn", 2)
    end
  end,
}

weiwenzhugezhi:addSkill(mingchao)
Fk:loadTranslationTable{
  ["wk_heg__weiwenzhugezhi"] = "卫温诸葛直",
  ["#wk_heg__weiwenzhugezhi"] = "谜络长洲",
  ["designer:wk_heg__weiwenzhugezhi"] = "祭祀",

  ["wk_heg__mingchao"] = "鸣潮",
  [":wk_heg__mingchao"] = "出牌阶段，你可选择一项：1.展示X张此回合未展示的手牌，然后使用其中一张牌；" ..
  "2.弃置X张此回合未展示的手牌，然后摸一张牌。你不能以此法连续选择相同项。（X为此回合发动此技能次数+1）",

  ["@@wk_heg__mingchao_shown-inhand-turn"] = "鸣潮",

  ["wk_heg__mingchao_show"] = "展示牌，然后使用其中一张牌",
  ["wk_heg__mingchao_discard"] = "弃置牌，然后摸一张牌",
  ["#wk_heg__mingchao"] = "鸣潮：你可以展示或弃置此回合未展示过的牌，然后执行对应效果",

  ["$wk_heg__mingchao1"] = "宦海沉浮，生死难料！",
  ["$wk_heg__mingchao2"] = "跨海南征，波涛起浮。",
  ["~wk_heg__weiwenzhugezhi"] = "吾皆海岱清士，岂料生死易逝……",
}

local luzhi = General(extension, "wk_heg__luzhi", "qun", 3)
local zhenliang = fk.CreateTriggerSkill{
  name = "wk_heg__zhenliang",
  anim_type = "special",
  events = {fk.GeneralRevealed, fk.GeneralHidden, "fk.GeneralRemoved", "fk.GeneralTransformed"},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and not target.dead
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, data, "#wk_heg__zhenliang-ask::" .. target.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if not target:isNude() then
      room:askForDiscard(target, 1, 1, true, self.name, false)
    end
    local choices = {"Cancel"}
    if (player.general == "wk_heg__luzhi" or player.deputyGeneral == "wk_heg__luzhi") and target:getMark("@wk_give_deputy") == 0 then
      table.insert(choices, 1, "wk_heg__zhenliang-give")
    end
    if room:askForChoice(target, choices, self.name) ~= "Cancel" then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
      if player.dead or target.dead then return end
      local isDeputy = H.inGeneralSkills(player, self.name)
      if isDeputy then
        DoGiveDeputy(room, player, target, "wk_heg__luzhi", player.kingdom, isDeputy == "d")
      end
      -- room:setPlayerMark(player, "wk_give_deputy_luzhi", 1)
    end
  end,
}

-- local zhenliang_delay = fk.CreateTriggerSkill{
--   name = "#wk_heg__zhenliang_delay",
--   anim_type = "special",
--   events = {fk.TurnStart},
--   can_trigger = function(self, event, target, player, data)
--     return target:getMark("wk_give_deputy_luzhi") == 1 and player:getMark("@wk_give_deputy") == "wk_heg__luzhi"
--   end,
--   on_cost = Util.TrueFunc,
--   on_use = function(self, event, target, player, data)
--     StopGiveDeputy(player.room, player, self.name)
--     player.room:setPlayerMark(target, "wk_give_deputy_luzhi", 0)
--   end,
-- }

local zhenliang_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__zhenliang_delay",
  anim_type = "special",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return player == player.room.current and player:getMark("@wk_give_deputy") == "wk_heg__luzhi"
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    StopGiveDeputy(player.room, player, self.name)
    -- player.room:setPlayerMark(target, "wk_give_deputy_luzhi", 0)
  end,
}

local function doImperialOrder(room, target)
  if target.dead then return end
  local all_choices = {"IO_reveal", "IO_discard", "IO_hplose"}
  local choices = table.clone(all_choices)
  if target.hp < 1 then table.remove(choices) end
  if table.every(target:getCardIds{Player.Equip, Player.Hand}, function(id) return Fk:getCardById(id).type ~= Card.TypeEquip or target:prohibitDiscard(Fk:getCardById(id)) end) then
    table.remove(choices, 2)
  end
  if (target.general ~= "anjiang" or target:prohibitReveal()) and (target.deputyGeneral ~= "anjiang" or target:prohibitReveal(true)) then
    table.remove(choices, 1)
  end
  if #choices == 0 then return false end
  local choice = room:askForChoice(target, choices, "imperial_order_skill", nil, false, all_choices)
  if choice == "IO_reveal" then
    H.askForRevealGenerals(room, target, "imperial_order_skill", true, true, false, false)
    target:drawCards(1, "imperial_order_skill")
  elseif choice == "IO_discard" then
    room:askForDiscard(target, 1, 1, true, "imperial_order_skill", false, ".|.|.|.|.|equip")
  else
    room:loseHp(target, 1, "imperial_order_skill")
  end
end

local lingli = fk.CreateActiveSkill{
  name = "wk_heg__lingli",
  anim_type = "control",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_num = 1,
  card_filter = function(self, to_select, selected)
    return #selected < 1 and Fk:getCardById(to_select).color == Card.Black and not Self:prohibitDiscard(to_select)
  end,
  target_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:throwCard(effect.cards, self.name, player, player)
    local targets = table.map(table.filter(room.alive_players, function(p)
      return p:getHandcardNum() > player:getHandcardNum() end), Util.IdMapper)
    room:sortPlayersByAction(targets)
    room:doIndicate(player.id, targets)
    for _, id in ipairs(targets) do
      local target = room:getPlayerById(id)
      doImperialOrder(room, target)
    end
  end,
}

zhenliang:addRelatedSkill(zhenliang_delay)
luzhi:addSkill(zhenliang)
luzhi:addSkill(lingli)

Fk:loadTranslationTable{
  ["wk_heg__luzhi"] = "卢植",
  ["designer:wk_heg__luzhi"] = "风萧",
  ["#wk_heg__luzhi"] = "",

  ["wk_heg__lingli"] = "令礼",
  [":wk_heg__lingli"] = "出牌阶段限一次，你可弃置一张黑色牌，然后令所有手牌数大于你的角色执行【敕令】的效果。",
  ["wk_heg__zhenliang"] = "贞良",
  [":wk_heg__zhenliang"] = "其他角色的武将牌状态改变后，你可令其弃置一张牌，然后其可受到你造成的1点伤害，令你借调此武将牌于其至其回合结束。"..
  "<font color = 'gray'>注：武将牌状态改变包括：明置、暗置、移除和变更。</font><br />"..
  "<font color = 'orange'>借调：借调角色执行借调流程时，移除对应的武将牌并将之置于目标角色的借调区内，视为该角色拥有此武将牌，借调区内的武将牌不为主副将且不能被移除、暗置和变更。"..
  "借调结束后，目标角色选择借调武将牌原本所属国家所有角色的一张士兵牌，令此士兵牌变更为借调武将牌。</font>",

  ["#wk_heg__zhenliang_delay"] = "贞良",

  ["#wk_heg__zhenliang-ask"] = "你可对 %dest 发动〖贞良〗",
  ["wk_heg__zhenliang-discard"] = "令 %src 弃牌",
  ["wk_heg__zhenliang-drawcard"] = "令 %src 摸牌",

  ["wk_heg__zhenliang-give"] = "借调 卢植",

  ["$wk_heg__lingli1"] = "吾之任，君之明举！",
  ["$wk_heg__lingli2"] = "得义真所救，吾任之必尽瘁以报。",
  ["$wk_heg__zhenliang1"] = "贞洁贤良，吾之本心。",
  ["$wk_heg__zhenliang2"] = "风霜以别草木之性，危乱而见贞良之节。",
  ["~wk_heg__luzhi"] = "泓泓眸子宿渊亭，不见蛾眉只见经。",
}

local yuantanyuanshang = General(extension, "wk_heg__yuantanyuanshang", "qun", 4)
local neifa = fk.CreateViewAsSkill{
  name = "wk_heg__neifa",
  anim_type = "special",
  card_filter = function(self, to_select, selected)
    if #selected == 0 then
      return true
    elseif #selected == 1 then
      return Fk:getCardById(to_select):compareColorWith(Fk:getCardById(selected[1]), true)
    else
      return false
    end
  end,
  view_as = function(self, cards)
    if #cards ~= 2 then
      return nil
    end
    local c = Fk:cloneCard("fight_together")
    c.skillName = self.name
    c:addSubcards(cards)
    return c
  end,
  enabled_at_play = function(self, player)
    return player:getMark("wk_heg__neifa-turn") == 0
  end,
}

local neifa_effect = fk.CreateTriggerSkill{
  name = "#wk_heg__neifa_effect",
  mute = true,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:getMark("wk_heg__neifa_damage") == 1 and player.chained and data.card and table.contains(data.card.skillNames, "wk_heg__neifa")
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p) return p.chained end), Util.IdMapper)
    if #targets > 0 then
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__neifa-choose")
      if #tos > 0 then
        local to = room:getPlayerById(tos[1])
        room:damage{
          from = player,
          to = to,
          damage = 1,
          skillName = self.name,
        }
      end
    end
    room:setPlayerMark(player, "wk_heg__neifa_damage", 0)
  end,

  refresh_events = {fk.TargetConfirmed},
  can_refresh = function(self, event, target, player, data)
    local room = player.room
    return data.card and table.contains(data.card.skillNames, "wk_heg__neifa")
      and (not table.find(TargetGroup:getRealTargets(data.tos), function(id) return not room:getPlayerById(id).chained end) or not player.chained)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if not table.find(TargetGroup:getRealTargets(data.tos), function(id) return not room:getPlayerById(id).chained end) then
      room:setPlayerMark(player, "wk_heg__neifa-turn", 1)
    end
    if not player.chained then
      room:setPlayerMark(player, "wk_heg__neifa_damage", 1)
    end
  end,
}

neifa:addRelatedSkill(neifa_effect)
yuantanyuanshang:addSkill(neifa)
Fk:loadTranslationTable{
  ["wk_heg__yuantanyuanshang"] = "袁谭袁尚",
  ["#wk_heg__yuantanyuanshang"] = "兄弟阋墙",
  ["designer:wk_heg__yuantanyuanshang"] = "静谦",
  
  ["wk_heg__neifa"] = "内伐",
  [":wk_heg__neifa"] = "你可将两张颜色不同的牌当【勠力同心】使用，此牌结算后若你因此横置，你可以对一名横置的角色造成1点伤害，若没有角色因此横置，此技能失效至本回合结束。",

  ["$wk_heg__neifa1"] = "自相恩残，相煎何急。",
  ["$wk_heg__neifa2"] = "同室内伐，贻笑外人。",
  ["~wk_heg__yuantanyuanshang"] = "兄弟难齐心，该有此果。",
}

return extension
